package com.dataStructure.array;


import java.util.Collection;
public class MyArrayList<E>  {
    private int size;
    private E[] array;

    public MyArrayList() {
        array = (E[]) new Object[10];
    }


    public boolean add(E element) {
        if (size >= array.length) {
            E[] objects = (E[]) new Object[size * 2];
            System.arraycopy(array,0,objects,0,size);
            array = objects;
            size++;
        }
        else {
            array[size] = element;
        }
        return true;
    }


    public E get(int index) {
        if (index < 0 || index > size) {
            throw new IndexOutOfBoundsException("下标值超出限制");
        }
        return array[index];
    }


    public E set (int index,E element) {
        E e = this.get(index);
        array[index] = element;
        return e;
    }

    public int indexOf(Object object) {
        for (int i = 0; i < size;i++) {
            if (object.equals(array[i])) {
                return i;
            }
        }

        return -1;
    }


    public E remove(int index) {
        E e = this.get(index);
        for (int i = index; i < size-1;i++ ) {
            array[i] = array[i+1];
        }
        size--;
        return e;
    }


    public void add(int index,E element) {
        if (index > size || index < 0) {
            throw new IndexOutOfBoundsException("下标值超出限制");
        }

        //这个add增添size大小
        this.add(element);

        for (int i = size -1;i > index;i--) {
            array[i] = array[i-1];
        }
        array[index] = element;

    }

    public boolean removeAll(Collection<?> collection) {

        boolean flag = true;
        for (Object o : collection) {
            //这个与运算
            flag &= this.remove(o) ;
        }
        return flag;
    }


    public boolean remove(Object obj) {
        int i = this.indexOf(obj);

        if (i == -1) {
            return false;
        }
        this.remove(i);
        return true;

    }


}
